//
//  ActionServiceManager.swift
//  home
//  动作-服务管理
//
//  Created by Yun Zeng on 2019/8/7.
//  Copyright © 2019 Yun Zeng. All rights reserved.
//

import Foundation

extension HMService {
    static func copy(service: HMService) -> HMService {
        let sev = HMService(id: service.id, type: service.type, characteristics: [])
        for characteristic in service.characteristics {
            let char = HMCharacteristic(id: characteristic.id, type: characteristic.type, format: characteristic.format)
            char.unit = characteristic.unit
            char.maxValue = characteristic.maxValue
            char.minValue = characteristic.minValue
            char.stepValue = characteristic.stepValue
            sev.characteristics.append(char)
        }
        return sev
    }
}

extension Service {
    static func copy(service: Service) -> Service {
        let sev = Service(service: service.instance!)!
        sev.state = .online
        sev.name = service.name
        sev.icon = service.icon
        sev.roomId = service.roomId
        sev.notify = service.notify
        sev.manager = nil
        sev.instance = HMService.copy(service: service.instance!)
        sev.room = service.room
        sev.home = service.home
        return sev
    }
    
    func patchAction(action: HomeAction) -> Bool {
        for characteristic in self.instance!.characteristics {
            if characteristic.id == action.cid {
                characteristic.value = action.value
                //Logger.Info("target: \(action)")
                //Logger.Info("characteristic: \(characteristic)")
                return true
            }
        }
        return false
    }
    
}

class ActionsServiceManager {
    var actions: [HomeAction]
    var services: [ServiceCellDelegate]
    
    init(actions: [HomeAction], home: Home) {
        self.actions = actions
        self.services = [ServiceCellDelegate]()
        
        var targetServices = Set<Service>()
        // 根据动作集合找到目标服务
        for action in actions {
            if let service = home.serviceManager.findService(aid: action.aid, sid: action.sid) {
                targetServices.insert(service)
            }
        }
        
        // 将要操作的服务复制一份，以方便进行状态匹配
        for service in targetServices {
            let copy = Service.copy(service: service)
            let custom = HMServiceType.getCustomService(service: copy)
            self.services.append(custom)
        }
        
        // 将动作写入复制的服务中，以匹配状态
        for action in actions {
            for target in self.services {
                if target.service.aid == action.aid && target.service.sid == action.sid {
                    _ = target.service.patchAction(action: action)
                }
            }
        }
    }
}
